package com.didispace;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

public class RabbitMqConnectionFactory {
	@Configuration
	@ConditionalOnMissingBean(ConnectionFactory.class)
	@AutoConfigureBefore({SimpleRabbitListenerContainerFactory.class,RabbitMessagingTemplate.class})
	protected static class RabbitConnectionFactoryCreator {

		@Bean("connectionFactory")
		public ConnectionFactory rabbitConnectionFactory(RabbitProperties config)
				throws Exception {
			
			List<CachingConnectionFactory>connectionFactoryList = new ArrayList<>();
			String addressesStr = config.getAddresses();
			String[] addresses = StringUtils.commaDelimitedListToStringArray(addressesStr) ;
			int addSize = addresses.length;
			System.out.println("addresses size is:"+addSize+": "+addresses.toString());
			Random random = new Random(System.currentTimeMillis());
			for(int i = 0;i<addSize;i++){
				RabbitConnectionFactoryBean factory = new RabbitConnectionFactoryBean();
				System.out.println("addresses size is:"+addSize+": "+addresses[i].toString());
				if (config.determineHost() != null) {
					factory.setHost(addresses[i].substring(0, addresses[i].indexOf(":")));
				}
				String portStr = addresses[i].substring(addresses[i].indexOf(":")+1);
				int port = Integer.parseInt(portStr);
				factory.setPort(port);
				System.out.println(addresses[i].substring(0, addresses[i].indexOf(":"))+" :"+port);
				if (config.determineUsername() != null) {
					factory.setUsername(config.determineUsername());
				}
				if (config.determinePassword() != null) {
					factory.setPassword(config.determinePassword());
				}
				if (config.determineVirtualHost() != null) {
					factory.setVirtualHost(config.determineVirtualHost());
				}
				if (config.getRequestedHeartbeat() != null) {
					factory.setRequestedHeartbeat(config.getRequestedHeartbeat());
				}
				RabbitProperties.Ssl ssl = config.getSsl();
				if (ssl.isEnabled()) {
					factory.setUseSSL(true);
					if (ssl.getAlgorithm() != null) {
						factory.setSslAlgorithm(ssl.getAlgorithm());
					}
					factory.setKeyStore(ssl.getKeyStore());
					factory.setKeyStorePassphrase(ssl.getKeyStorePassword());
					factory.setTrustStore(ssl.getTrustStore());
					factory.setTrustStorePassphrase(ssl.getTrustStorePassword());
				}
				if (config.getConnectionTimeout() != null) {
					factory.setConnectionTimeout(config.getConnectionTimeout());
				}
				factory.afterPropertiesSet();
				CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
						factory.getObject());
//				connectionFactory.setAddresses(addressesStr);
				connectionFactory.setPublisherConfirms(config.isPublisherConfirms());
				connectionFactory.setPublisherReturns(config.isPublisherReturns());
				if (config.getCache().getChannel().getSize() != null) {
					connectionFactory
							.setChannelCacheSize(config.getCache().getChannel().getSize());
				}
				if (config.getCache().getConnection().getMode() != null) {
					connectionFactory
							.setCacheMode(config.getCache().getConnection().getMode());
				}
				if (config.getCache().getConnection().getSize() != null) {
					connectionFactory.setConnectionCacheSize(
							config.getCache().getConnection().getSize());
				}
				if (config.getCache().getChannel().getCheckoutTimeout() != null) {
					connectionFactory.setChannelCheckoutTimeout(
							config.getCache().getChannel().getCheckoutTimeout());
				}
				connectionFactoryList.add(connectionFactory);
			}
			ConnectionFactory connectionFactory = new MyConnectionFactory(connectionFactoryList);
			
			return connectionFactory;
//			return connectionFactoryList.get(1);
		}
		
		@Bean
		@ConditionalOnSingleCandidate(ConnectionFactory.class)
		public RabbitAdmin rabbitAdmin(@Qualifier("connectionFactory")ConnectionFactory connectionFactory){
			System.out.println("self rabbitAdmin");
			return new RabbitAdmin(connectionFactory);
		}
	}
	
}
